package com.dgut.sales.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dgut.sales.bean.Customer;
import com.dgut.sales.dynamic.sql.bean.CustomerSearch;
import com.dgut.sales.service.CustomerService;

@Controller
@RequestMapping("/customer")
public class CustomerControllerr {
	
	@Autowired
	private CustomerService service;
	
	
	@ModelAttribute
	public void prepareModel(Model model) {
		model.addAttribute("customer", new Customer());
	}
	
	@GetMapping("/list")
	public String list(Model model) {
		List<Customer> customers = service.getAllCustomer();
		model.addAttribute("customers", customers);
		return "/customer/customerList";
	}
	
	@PostMapping("/inputCustomer")
	public String inputCustomer(Model model) {
		model.addAttribute("customer", new Customer());
		return "/customer/inputCustomer";
	}
	
	@PostMapping("/addCustomer")
	public String addCustomer(@ModelAttribute Customer customer) {
		service.addCustomer(customer);
		return "redirect:/customer/list";
	}
	
	
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") Integer id, Model model) {
		Customer customer = service.getCustomerById(id);
		model.addAttribute("customer", customer);
		return"customer/editCustomer";
	}
	
	@PutMapping("/update")
	public String update(@ModelAttribute Customer customer) {
		service.update(customer);
		return "redirect:/customer/list";
	}
	
	@GetMapping("/deleteCustomer/{id}")
	public String deleteCustomer(@PathVariable("id") Integer id){
		service.deleteCustomer(id);
		return "redirect:/customer/list";
	}
	
	@PostMapping("/inputCondition")
	public String inputCondition(Model model) {
		model.addAttribute("searchCustomer", new CustomerSearch());
		return "customer/inputCondition";
	}
	
	
	@PostMapping("/search")
	public String search(@ModelAttribute CustomerSearch customerSearch, Model model) {
		List<Customer> customers = service.searchCustomer(customerSearch);
		model.addAttribute("customers", customers);
		return "customer/searchResult";
	}
	
	@GetMapping("/statistics")
	public String statistics(Model model) {
		List<Map<String, Object>> fromCustomerStatistics = service.searchCustomerWithMoney();
		model.addAttribute("fromCustomerStatistics", fromCustomerStatistics);
		return "statistics/fromCustomer";
	}
}
